import json
import tkinter as tk
from tkinter import filedialog

def json_to_jsonl(json_file, jsonl_file):
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    with open(jsonl_file, 'w', encoding='utf-8') as f:
        for item in data:
            f.write(json.dumps(item, ensure_ascii=False) + '\n')
    print(f"转换完成: {json_file} -> {jsonl_file}")

def jsonl_to_json(jsonl_file, json_file):
    with open(jsonl_file, 'r', encoding='utf-8') as f:
        data = [json.loads(line) for line in f]
    
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    print(f"转换完成: {jsonl_file} -> {json_file}")

def select_file():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(filetypes=[('JSON & JSONL', '*.json;*.jsonl')])
    if not file_path:
        print("未选择文件。")
        return
    
    if file_path.endswith('.json'):
        jsonl_path = file_path.replace('.json', '.jsonl')
        json_to_jsonl(file_path, jsonl_path)
    elif file_path.endswith('.jsonl'):
        json_path = file_path.replace('.jsonl', '.json')
        jsonl_to_json(file_path, json_path)
    else:
        print("请选择 JSON 或 JSONL 文件。")

if __name__ == "__main__":
    select_file()
